﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using IndustrialSmokeCalc.SmokeCalcWCF;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Telerik.Charting;
using Telerik.Windows.Controls;

namespace IndustrialSmokeCalc
{
    public partial class Chart : PhoneApplicationPage
    {
        private double[] value;
        public Chart()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            FillData();
            GetOpacityStatistic();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            double plotAreaWidth = chart.radChart.PlotAreaClip.Width;
            double zoomWidth = chart.radChart.Zoom.Width * plotAreaWidth;
            double maxOffsetX = plotAreaWidth - zoomWidth;
            chart.radChart.PanOffset = new Point(maxOffsetX, 0);
        }

        private void toggleBenchmark_Checked(object sender, RoutedEventArgs e)
        {
            toggleBenchmark.Content = "On";
            legendBenchmark.Visibility = Visibility.Visible;

            double topHighest = CalculateTopMargin(chart.radChart.ActualHeight, value[0]);
            chart.lineHighest.Margin = new Thickness(43,12+topHighest,35,0);
            chart.lineHighest.Visibility = Visibility.Visible;

            double topAverage = CalculateTopMargin(chart.radChart.ActualHeight, value[2]);
            chart.lineAverage.Margin = new Thickness(43, 12 + topAverage, 35, 0);
            chart.lineAverage.Visibility = Visibility.Visible;

            double topLowest = CalculateTopMargin(chart.radChart.ActualHeight, value[1]);
            chart.lineLowest.Margin = new Thickness(43, 12 + topLowest, 35, 0);
            chart.lineLowest.Visibility = Visibility.Visible;
        }

        private double CalculateTopMargin(double height, double val)
        {
            return (height - 45.0) / 100.0 * (100.0 - val);
        }

        private void toggleBenchmark_Unchecked(object sender, RoutedEventArgs e)
        {
            toggleBenchmark.Content = "Off";
            legendBenchmark.Visibility = Visibility.Collapsed;
            chart.lineHighest.Visibility = Visibility.Collapsed;
            chart.lineAverage.Visibility = Visibility.Collapsed;
            chart.lineLowest.Visibility = Visibility.Collapsed;
        }

        private void GetOpacityStatistic()
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.GetOpacityStatisticCompleted += GetOpacityStatisticCompleted;
            client.GetOpacityStatisticAsync();
        }

        private void GetOpacityStatisticCompleted(object sender, GetOpacityStatisticCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Tidak dapat melakukan koneksi ke server.\r\nCoba periksa koneksi internet anda.");
                NavigationService.Navigate(new Uri("/Menu.xaml", UriKind.Relative));
            }
            else if (e.Result != null)
            {
                value = new double[]{ e.Result[0], e.Result[1], e.Result[2] };
                toggleBenchmark.IsEnabled = true;
            }
        }

        private void FillData()
        {
            List<ChartBusinessObject> itemsSource = new List<ChartBusinessObject>();
            int count = DataSingleton.Instance.MeasurementList.Count;

            ChartBusinessObject model = new ChartBusinessObject();

            foreach (var item in DataSingleton.Instance.MeasurementList)
            {
                model = new ChartBusinessObject();
                model.Value = double.Parse(item.MeasurementResultRingelmann);
                model.Category = item.MeasurementDate;
                itemsSource.Add(model);
            }

            chart.radChart.Zoom = new Size((count / 8) + 1, 1);
            chart.radChart.MaxZoom = new Size((count / 8) + 2, 1);
            chart.radChart.DataContext = itemsSource;
        }

        private void ChartTrackBallBehavior_TrackInfoUpdated(object sender, TrackBallInfoEventArgs e)
        {
            CategoricalDataPoint dataPoint = e.Context.ClosestDataPoint.DataPoint as CategoricalDataPoint;
            e.Context.ClosestDataPoint.DisplayHeader = "Detail Pengamatan";
            e.Context.ClosestDataPoint.DisplayContent = "Tanggal: " + dataPoint.Category + Environment.NewLine + "Nilai opasitas: " + dataPoint.Value + "";
        }

        private void ChartTooltipBehavior_ContextNeeded(object sender, TooltipContextNeededEventArgs e)
        {
            CategoricalDataPoint dataPoint = (CategoricalDataPoint)e.DefaultContext.ClosestDataPoint.DataPoint;
            e.Context = new ChartBusinessObject
            {
                Value = (double)dataPoint.Value,
                Category = dataPoint.Category.ToString(),
            };
        }
    }
}